package com.lhm.controller;


import com.lhm.entity.Book;
import com.lhm.entity.LargeFile;
import com.lhm.service.BookService;
import com.lhm.service.LargeFileService;
import com.lhm.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

//@CrossOrigin
@RestController
@RequestMapping("/api/adm/book")
public class BookController {
    @Autowired
    BookService bookService;
    @Autowired
    LargeFileService largeFileService;

    //根据bookid查找
    @RequestMapping("findById/{bookid}")
    public Map<String,Object> findById(@PathVariable Integer bookid){
        Book book = bookService.findById(bookid);
        return RespJson.pack(200,"ok",book);
    }

    //查找全部
    @RequestMapping("/findAll")
    public Map<String,Object > findAll(){
        List<Book> lst = bookService.findAll();
        return RespJson.pack(200,"ok",lst);
    }

    //添加
    @RequestMapping("/addBook")
    public Map<String,Object> addBook(@RequestParam("pic")MultipartFile file,Book book) throws IOException {
        LargeFile largeFile = new LargeFile();
        Map<String, Object> map = new HashMap<>();
        if (book.getId()==null||book.getId()==0){
            if (file!=null &&file.getSize()>0){
                largeFile.setFilename(file.getOriginalFilename());
                byte[] buf = file.getBytes();
                largeFile.setContent(buf);
                String s=UUID.randomUUID().toString();
                largeFile.setId(s);
            }
            if (largeFile.getId()!=null){
                book.setPicture(largeFile.getId());
                largeFileService.addLargefile(largeFile);
            }
            bookService.addBook(book);
        }
        if (book.getId()>0){
            if (file!=null && file.getSize()>0){
                Book book1 = bookService.findById(book.getId());
                System.out.println(book1);
                largeFileService.delete(book1.getPicture());//删除旧图片


                largeFile.setFilename(file.getOriginalFilename());
                byte[] buf = file.getBytes();
                largeFile.setContent(buf);
                String s=UUID.randomUUID().toString();
                largeFile.setId(s);
            }
            if (largeFile.getId()!=null){
                book.setPicture(largeFile.getId());
                largeFileService.addLargefile(largeFile);
            }
            bookService.update(book);
        }
        book = bookService.findById(book.getId());
        System.out.println("添加的id="+book.getId());
        map.put("book", book);
        return RespJson.pack(200,"更新或添加成功...",map);
    }
    //显示图片
    @RequestMapping("/show/{id}")
    public void show(@PathVariable String id ,HttpServletResponse response){
        if (id == null)
            return;
        LargeFile largeFile = largeFileService.findById(id);
        System.out.println(largeFile);
        byte[] buf = (byte[])largeFile.getContent();
        try {
            response.setContentType("image/jpeg");
            response.getOutputStream().write(buf);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //分页
    @RequestMapping("/findByPage/{start}/{num}")
    public Map<String, Object> findPages_book(@PathVariable("start") Integer start, @PathVariable("num") Integer num) {
        Map<String, Object> map = new HashMap<>();
                                            //起始页 1， 每页几行
        List<Book> lst = bookService.findPage((start - 1)*num, num, 0);
        map.put("books", lst);
        // 不用查找类型，只显示页数
        int count = bookService.getCount(0);
        map.put("total", count);
        return RespJson.pack(200, "", map);
    }
    /**
     * 自动转换日期类型的字段格式
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
}
